package com.example.provider.service.impl;

import com.example.common.entity.Demand;
import com.example.common.entity.WorkRoom;
import com.example.provider.dao.WorkroomDao;
import com.example.provider.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private WorkroomDao workroomDao;

    /**
     * 根据标签搜索项目(需求)
     * @param lable
     * @return
     */
    public List<Demand> SearchByLable(String lable) throws IOException {
        SearchRequest request = new SearchRequest("demo_demand");
        //构建搜索条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        FuzzyQueryBuilder queryBuilder =
                QueryBuilders.fuzzyQuery("lable.keyword", lable);
        builder.query(queryBuilder);
        request.source(builder);
        SearchResponse response =
                restHighLevelClient.search(request, RequestOptions.DEFAULT);
        List<Demand> demands = new ArrayList<>();
        //封装成对象返回
        for (SearchHit hit : response.getHits().getHits()) {
            Map map = hit.getSourceAsMap();
            Demand d = new Demand((long)map.get("id"), map.get("lable").toString(),
                    (double)map.get("money"), map.get("phone").toString(), (int)map.get("status"),
                    map.get("description").toString(), (int)map.get("companyId"));
            demands.add(d);
        }
        return demands;
    }

    /**
     * 根据标签搜索工作室
     * @param lable 搜索标签
     * @return
     */
    public List<WorkRoom> SearchWorkroomByLable(String lable) {
        return workroomDao.searchWorkroomByLable("%" + lable + "%");
    }

    /**
     * 根据名称搜索工作室
     * @param name 搜索工作室名
     * @return
     */
    public List<WorkRoom> SearchWorkroomByName(String name) {
        return workroomDao.SearchWorkroomByName("%" + name + "%");
    }
}
